package com.alks.function.controller.task;


import com.alks.entity.data.entity.PcCuttingProcessV;
import com.alks.entity.data.i18n.TranslateService;
import com.alks.common.service.RedisService;
import com.alks.entity.data.entity.YfOrderPartName;
import com.alks.function.data.request.chengKong.PartRequest;
import com.alks.function.mapper.SdStyleMapper;
import com.alks.function.mapper.chengKong.PartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PartTask implements TranslateService {

    @Resource
    private RedisService redisService;

    @Resource
    private PartMapper partMapper;

    @Autowired
    private SdStyleMapper sdStyleMapper;

    private static final String REDIS_PREFIX = "part:lang:translation:";

    /**
     * 启动立即执行一次
     */
    @EventListener(ApplicationReadyEvent.class)
    public void initOnStartup() {
        List<YfOrderPartName> partList = partMapper.getPartList(new PartRequest());
        if (partList == null || partList.isEmpty()) return;
        String redisKey = REDIS_PREFIX + "vi";
        redisService.delete(redisKey);
        HashOperations<String, String, String> hashOps = redisService.opsForHash();
        partList.forEach(item -> {
            hashOps.put(redisKey, item.getPartName(), item.getVPartName());
        });
        String redisCnKey = REDIS_PREFIX + "zh-cn";
        redisService.delete(redisCnKey);
        List<PcCuttingProcessV> processList = sdStyleMapper.getPcProcess();
        if (processList == null || processList.isEmpty()) return;
        HashOperations<String, String, String> processOps = redisService.opsForHash();
        processList.forEach(item -> {
            processOps.put(redisCnKey, item.getProcessV(), item.getProcess());
        });
    }

    /**
     * 翻译接口：从Redis读取翻译
     */
    @Override
    public String translate(String key, String language) {
        if (key == null || key.isEmpty()) return null;
        String redisKey = REDIS_PREFIX + language;
        HashOperations<String, String, String> hashOps = redisService.opsForHash();
        return hashOps.get(redisKey, key);
    }
}
